package com.ocm.controller.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.ocm.controller.util.OCMUtil;
import com.ocm.core.dto.GroupDto;
import com.ocm.core.dto.UserInfoDto;
import com.ocm.core.service.SecurityService;

@Component("securityValidator")
public class SecurityValidator implements Validator {

   private SecurityService securityService;

   @Autowired
   public SecurityValidator(@Qualifier("securityService") SecurityService securityService) {
      this.securityService = securityService;
   }

   public boolean supports(Class<?> group) {
      return GroupDto.class.isAssignableFrom(group);
   }

   public void validate(Object object, Errors errors) {
      validateGroup((GroupDto)object, null, errors);
   }

   public void validateGroup(GroupDto groupDto, GroupDto oldGroupDto, Errors errors) {
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "authority", "err.required");
      String groupname = groupDto.getUsername();
      if (!errors.hasFieldErrors("username")) {
         if (StringUtils.containsWhitespace(groupname)) {
            errors.rejectValue("username", "err.containsWhitespace");
         }
      }
      if (!errors.hasFieldErrors("username")) {
         boolean hasNotSame = ((!OCMUtil.hasIDNotExist(groupDto.getId()) && oldGroupDto.getUsername().equals(groupDto.getUsername())))?false:true;
         if (hasNotSame && this.securityService.hasExistGroupName(groupname)) {
            errors.rejectValue("username", "err.unique");
         }
      }
   }
   
   public void validateUser(UserInfoDto userInfoDto, UserInfoDto oldUserInfoDto , Errors errors) {
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "err.required");
      String username = userInfoDto.getUsername();
      if (!errors.hasFieldErrors("username")) {
         if (StringUtils.containsWhitespace(username)) {
            errors.rejectValue("username", "err.containsWhitespace");
         }
      }
      if (!errors.hasFieldErrors("username")) {
         boolean hasNotSame = ((!OCMUtil.hasIDNotExist(userInfoDto.getId()) && oldUserInfoDto.getUsername().equals(userInfoDto.getUsername())))?false:true; 
         if ( hasNotSame && this.securityService.hasExistUserName(username)) {
            errors.rejectValue("username", "err.unique");
         }
      }
   }
}
